<template>
    <rx-layout>
        <div slot="left" width="220" showButton="true">
            <rx-fit>
                <rx-category-treeeditor
                    cat-key="FORM"
                    :statisticConfig="statisticConfig"
                    :edit="true"
                    @handSelect="handSelect"
                    :async="true"
                    v-if="isShowManageTree"
                    :isAdmin="isManageToTree"
                    :checkToDel="true"
                ></rx-category-treeeditor>
            </rx-fit>
        </div>
        <div slot="center" style>
            <rx-fit :isheader="isheader">
                <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
                    <div class="table-operator">
                        <a-button type="primary" icon="plus" v-if="findAuthRight('add')" @click="addDialog(false)">{{$ti18('rxList.newBtn','新建')}}</a-button>
                        <a-button icon="plus" v-if="findAuthRight('add')" @click="addDialog(true)">{{i18n('list.newTreeDialog','添加树型对话框')}}</a-button>
                        <a-button type="primary" v-if="!isAppDevelop && selectedRowKeys.length > 0 " icon="redo"
                                  @click="changeApp('FORM',selectedRows,'pkId','name','appId','treeId',changeAppId)">
                            {{i18n('list.changeApp','变更应用')}}
                        </a-button>
                        <a-button v-if="selectedRowKeys.length > 0"
                                  type="primary"
                                  icon="switcher" @click="openCategoryDialog">
                            {{$ti18('rxList.changeCategory','切换分类')}}
                        </a-button>
                        <a-dropdown>
                            <a-button> {{$ti18('rxList.moreBtn','更多')}}
                                <a-icon type="down"/>
                            </a-button>
                            <a-menu slot="overlay">
                                <a-menu-item key="5" @click="doImport" v-if="findAuthRight('add')"><i
                                    class="iconfont icondaoru"></i>{{$ti18('rxList.importBtn','导入')}}
                                </a-menu-item>
                                <a-sub-menu>
                                    <span slot="title"><i class="iconfont icondaochu"></i>{{$ti18('rxList.exportBtn','导出')}}</span>
                                    <a-menu-item @click="doExport('1')"><i class="iconfont icondaochu"></i>{{i18n('list.exportSelected','导出选中')}}
                                    </a-menu-item>
                                    <a-menu-item @click="doExport('2')"><i class="iconfont icondaochu"></i>{{i18n('list.exportResult','导出查询结果')}}
                                    </a-menu-item>
                                </a-sub-menu>
                                <a-menu-item
                                    key="6"
                                    @click="editOneDialog"
                                    v-if="findAuthRight('edit') && editEnable && selectedRowKeys.length > 0"
                                    alias="formRuleEdit"
                                    :butn-type="'primary'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="edit"/>
                                    {{$ti18('rxList.editBtn','编辑')}}
                                </a-menu-item>
                                <a-menu-item
                                    key="7"
                                    @click="delByIds(selectedRowKeys)"
                                    v-if="findAuthRight('delete') && removeEnable && selectedRowKeys.length > 0"
                                    alias="formRuleDelete"
                                    :butn-type="'danger'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="delete"/>
                                    {{$ti18('rxList.delBtn','删除')}}
                                </a-menu-item>
                                <a-menu-item
                                    key="8"
                                    @click="changeExport(exportConf)"
                                    v-if="selectedRowKeys.length > 0"
                                    alias="formRuleDelete"
                                    :butn-type="'primary'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="switcher"/>
                                    {{$ti18('rxList.changeExport','切换导出')}}
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </div>
                    <span class="search-btn-box" v-if="!isheader">
                        <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>{{$ti18('rxList.leachBtn','过滤')}}</span>
                    </span>
                </div>
                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.name','名称')">
                                    <a-input :placeholder="i18n('form.name','名称','input')" v-model="queryParam.Q_NAME__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.markKey','标识键')">
                                    <a-input :placeholder="i18n('form.markKey','标识键','input')" v-model="queryParam.Q_KEY__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="!curApp.appId">
                                <a-form-item :label="$ti18('rxForm.appId', '应用')">
                                    <rx-search-app @change="appChange" v-model="searchApps">
                                    </rx-search-app>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    ref="table"
                    :bordered="isBorder"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="10"
                    url="/api-form/form/core/formBoList/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10','30','40']"
                    id-field="id"
                    :loadDataOnstart="true"
                    @selectChange="onSelectChange"
                >
                    <span slot="exportApp">
                         {{ exportI18n('export.isExport','导出') }}
                        <export-app/>
                    </span>
                    <span slot="isTreeDlg" slot-scope="{text, record}">
                        <a-tag :color="isTreeDlgMap[text!=null?text:'NO'].color">
                            <span>{{ isTreeDlgMap[text != null ? text : 'NO'].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="isLeftTree" slot-scope="{text, record}">
                        <a-tag :color="isLeftTreeMap[text].color">
                            <span>{{ isLeftTreeMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="isPage" slot-scope="{text, record}">
                        <a-tag :color="isPageMap[text].color">
                            <span>{{ isPageMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="appId" slot-scope="{ text, record }">
                        {{allApps[text]?$i18(allApps[text].appName,'应用名称'):$ti18('rxList.noAppName','无')}}
                    </span>
                    <span slot="isExport" slot-scope="{ text, record }">
                        <a-tag :color="text == 1 ? 'green' : 'red'">
                            <span>{{ text == 1 ? exportI18n('export.yes','是') : exportI18n('export.no','否') }}</span>
                        </a-tag>
                    </span>
                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                        <span v-if="findAuthRight('edit') && editEnable" @click.stop="editDialog(record)">{{$ti18('rxList.editBtn','编辑')}}</span>
                        <span v-if="findAuthRight('delete') && removeEnable" @click.stop="delByIds([record.id])">{{$ti18('rxList.delBtn','删除')}}</span>
                        <span @click.stop="preview(record)">{{$ti18('rxList.preview','预览')}}</span>
                        <span @click.stop="editHtml(record)">{{i18n('list.editCode','编辑代码')}}</span>
                        <span @click.stop="setExport(record,exportConf)">{{record.isExport == 1 ? exportI18n('export.noExport','不导出') : exportI18n('export.exported','导出')}}</span>
                        <span v-if="!curApp.appId" @click.stop="share(record)">{{$ti18('rxList.share','共享')}}</span>
                    </span>
                </rx-grid>
            </rx-fit>
            <a-modal :zIndex="99999" :title="i18n('generatePage','你确定要生成页面吗？')" v-model="remarkVisible" @ok="handleOk">
                <p>{{$ti18('rxForm.notes','备注')}}：</p>
                <br/>
                <p>
                    <a-textarea sty v-model="remark" :auto-size="{ minRows: 4}"></a-textarea>
                </p>
            </a-modal>
        </div>
    </rx-layout>
</template>

<script>
import FormBoListApi from '@/api/form/core/formBoList'
import FormBoListEdit from './FormBoListEdit'
import FormBoListTreeEdit from "./FormBoListTreeEdit"
import {BaseList, Dialog, Util} from "@lowcode/jpaas-common-lib";
import DialogBox from "../../../../assets/js/DialogBox";
import RxCategoryTreeeditor from "@/components/redxun/rx-category-treeeditor";
import FormImport from "@/views/modules/form/core/FormImport";
import changeAppJs from "@/views/modules/share/changeApp";
import {mapState} from "vuex";
import exportApp from "@/views/modules/share/exportApp";
import FormResourceShareApi from "@/api/form/core/formResourceShare";
import AppSearch from "@/views/modules/share/AppSearch";
import RxSearchApp from "@/views/modules/share/rx-search-app";
import SysAppApi from "@/api/system/core/sysApp";
import {openUrl} from "@/utils/util";
import SysTreeApi from "@/api/system/core/sysTree";
import switchExport from "@/utils/switchExport";
import ChangeCategory from "@/views/modules/share/ChangeCategory.js"
export default {
    name: 'FormBoListList',
    mixins: [BaseList,changeAppJs,AppSearch,switchExport,ChangeCategory],
    components: {
        RxCategoryTreeeditor,
        exportApp,
        RxSearchApp
    },
    props:["currentApp"],
    computed: {
        ...mapState({
            //所属应用
            allApps: state => state.appSetting ? state.appSetting.allApps : {}
        }),
    },
    filters: {},
    data() {
        return {
            columns: [
                {
                    title: this.$ti18('rxList.index','序号'),
                    type: 'indexColumn',
                    width: 60,
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'}
                },
                {title: this.i18n('form.name','名称'), dataIndex: 'name', width: 100},
                {title: this.i18n('form.markKey','标识键'), dataIndex: 'key', width: 100},
                {title: this.i18n('form.treeForm','树形'), dataIndex: 'isTreeDlg', scopedSlots: {customRender: 'isTreeDlg'}, width: 100},
                {title: this.i18n('form.paging','分页'), dataIndex: 'isPage', scopedSlots: {customRender: 'isPage'}, width: 100},
                {title: this.i18n('form.application','所属应用'), dataIndex: 'appId', width: 100, sortField: 'APP_ID_',scopedSlots: {customRender: 'appId'}},
                {
                    dataIndex: 'isExport',
                    slots: { title: 'exportApp' },
                    width: 100,
                    scopedSlots: {customRender: 'isExport'}
                },
                {title: this.i18n('form.createTime','创建时间'), dataIndex: 'createTime',  width: 120},
                {title: this.$ti18('rxList.action','操作'), width: 120, fixed:'right',dataIndex: 'action', scopedSlots: {customRender: 'action'}}
            ],
            curTree: {},
            QueryData: {},
            component: FormBoListEdit,
            comment: this.i18n('list.customDialog','自定义对话框'),
            widthHeight: ['1000px', '600px'],
            isTreeDlgMap: {
                "YES": {color: 'green', text: this.i18n('tree','树型')},
                "NO": {color: 'red', text: this.i18n('flat','平铺')}
            },
            isLeftTreeMap: {
                "YES": {color: 'green', text: this.i18n('yes','是')},
                "NO": {color: 'red', text: this.i18n('no','否')}
            },
            isPageMap: {
                "YES": {color: 'green', text: this.i18n('yes','是')},
                "NO": {color: 'red', text: this.i18n('no','否')}
            },
            remarkVisible:false,
            remark:"",
            modal:this,
            statisticConfig: {
                type:"static_form",
                table:"FORM_BO_LIST t",
                field:"TREE_ID_",
                whereConf:[{name:"IS_DIALOG_",type:"string",dateFormat:"",op:"=",value:"YES"}]
            },
            /**
             * 导出配置
             */
            exportConf:{
                Api:FormBoListApi,
                id:"id"
            },
            //变更分类配置
            categoryConfig:{
                Api:FormBoListApi,
                catKey:"FORM",
                gridRef:"table"
            }
        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
        this.needFilterAppId("isAppMenu");
        this.queryParam.Q_IS_DIALOG__S_EQ = "YES";
        this.columns=this.removeAppColumn(this.curApp.appId,this.columns)
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formBoListDialog", key);
        },
        exportI18n(name,text,key){
            return this.$ti18(name,text,"appExport",key);
        },
        //资源共享
        share(record){
            let self=this;
            FormResourceShareApi.getShareApps(record.id).then(res => {
                let initData=res.data;
                if(!initData){
                    initData=[];
                }
                self.showAppDialog(initData,record.id,record.key,record.name);
            });
        },
        showAppDialog(initData,resId,resKey,resName){
            Dialog.openSystemAppDialog({
                curVm: this, widthHeight: ['1150px', '735px'],
                data:{initSelected: initData,isDevelopApp:true,isSelectApp:true}
            }, function (self, data) {
                //保存共享信息
                FormResourceShareApi.saveShareApps(data.apps,resId,resKey,resName,"2").then(res => {
                    if (res.success && res.code == 200) {
                    }
                });
            })
        },
        delById(ids) {
            return FormBoListApi.del({ids: ids.join(',')});
        },
        getListByParams(parameter) {
            parameter.params.Q_IS_DIALOG__S_EQ = "YES" //查询为对话框的数据
            let appId = this.curApp.appId;
            if (appId) {
                parameter.params.Q_APP_ID__S_EQ = appId;
            }
            return FormBoListApi.query(parameter)
        },
        getAppQuery(){
            var query={};
            if(this.curApp.appId){
                query.appId=this.curApp.appId;
                query.appName=this.curApp.appName;
            }
            return query;
        },
        addDialog(isTree) {
            var self_=this
            let dsAlias = "";
            if(this.currentApp && this.currentApp.dataSource){
                dsAlias = JSON.parse(this.currentApp.dataSource).value;
            }
            let queryParams={catKey:'FORM',readKey:'read',isAdmin:this.isManageToTree,isGrant:true,appId:self_.curApp.appId}
            SysTreeApi.getTopNodesByCatKey(queryParams).then((res) => {
                if (res && res.length > 0){
                    let name=isTree? "FormBoListTreeEdit" :"FormBoListEdit";
                    let url=self_.$router.resolve({
                        name: name,
                        query: {
                            isDialog: "YES",
                            ...self_.getAppQuery(),
                            dsAlias: dsAlias
                        }
                    }).href;
                    window.open(url);
                }else {
                    self_.$message.error(self_.i18n('msa.noCategory','请先选择分类!'));
                }
            })
        },
        treeEdit(record) {
            this.$router.push({
                name: "FormBoListTreeEdit",
                query: {
                    pkId: record.pkId,
                    isDialog: "YES",
                    ...this.getAppQuery()
                }
            })
        },
        editDialog(record) {
            let name=record.isTreeDlg == "YES"? "FormBoListTreeEdit":"FormBoListEdit";
            let obj={
                name: name,
                query: {
                    pkId: record.pkId,
                    isDialog: "YES",
                    ...this.getAppQuery()
                }
            };
            let url=this.$router.resolve(obj).href;
            let target="formbodialog_" + record.pkId;

            window.open(url,target);
        },
        editOneDialog() {
            if (this.selectedRows.length > 0) {
                var record = this.selectedRows[0];
                if (record.isTreeDlg == "YES") {
                    this.treeEdit(record);
                } else {
                    this.$router.push({
                        name: "FormBoListEdit",
                        query: {
                            pkId: record.pkId,
                            isDialog: "YES",
                            ...this.getAppQuery()
                        }
                    })
                }
            }
        },
        preview(record) {
            let appId=record.appId;
            let ctxPath= process.env.VUE_APP_CONTEXT_MAIN;

            let url=`${ctxPath}/list/${record.key}?appId=${appId}`;
            let title=record.name;
            openUrl({url:url,title:title,curVm:this,widthHeight:['800px','600px'],dialogBox:true});

        },
        grant(record){
          var config={
            component:FormBoDatasEdit,
            title:this.i18n('list.grant','添加数据权限'),
            curVm:this,
            data:{listId:record.id,listName:record.name,appId:record.appId},
            widthHeight:['1400px','650px']
          };
          Util.open(config,function(action){});
        },
        editHtml(record) {
            DialogBox.editHtml(record.id, {
                curVm: this,
                widthHeight: ['1000px', '600px']
            },this.showModal)
        },
        showModal(self) {
            if (self) {
                this.modal = self;
            }
            this.remark = "";
            this.remarkVisible = true;
        },
        handleOk(){
            this.remarkVisible=false;
            if(this.modal && this.modal.saveHtml){
                this.modal.saveHtml(this.modal,this.remark);
            }
        },
        handSelect(curRow) {
            this.curTree = curRow
            var treeId = curRow.treeId;
            if (treeId != "0") {
                this.queryParam.Q_TREE_ID__S_EQ = treeId;
            } else {
                delete this.queryParam.Q_TREE_ID__S_EQ;
            }
            this.loadData(this.queryParam);
        },
        search() {
            this.$refs.table.loadData();
        },
        cancel() {
            this.$nextTick(() => {
                this.queryParam = {};
                this.queryParam.Q_IS_DIALOG__S_EQ = "YES";
                let appId = this.curApp.appId;
                if (appId) {
                    this.queryParam.Q_APP_ID__S_EQ = appId;
                }
                this.$nextTick(() => {
                    this.$refs[this.table].loadData();
                })
            })
        },
        closeSearchbar() {
            //关闭过滤弹窗；（点击X触发）
            this.fitSearch = false;
        },
        doExport(isSelected) {
            var exportList = [];
            //选中的导出
            if (isSelected == "1") {
                exportList = this.$refs.table.getSelectedRows();
                if (!exportList || exportList.length == 0) {
                    this.$warning({
                        title: this.i18n('warning','警告'),
                        content: this.i18n('selectRecord','请选择需要导出的记录！'),
                    });
                    return;
                }
                let solutionIds = []
                exportList.forEach((item) => {
                    solutionIds.push(item.id)
                })
                this.QueryData.params = {
                    ids: solutionIds.toString()
                }
            } else {
                // 导出所查询的
                this.QueryData.params = {
                    isQuery: 0,
                }
                this.QueryData.params = Object.assign(this.QueryData.params, this.queryParam)
            }
            if (this.$refs.table.dataAction == "") {
                this.$warning({
                    title: this.i18n('warning','警告'),
                    content: this.i18n('noData','该分类没有数据！'),
                });
                return;
            }
            FormBoListApi.listExport(this.QueryData)
        },
        doImport() {
            if (!this.curTree || !this.curTree.treeId) {
                this.$warning({
                    title: this.i18n('warning','警告'),
                    content: this.i18n('selectClass','请选择表单方案的分类！'),
                });
                return
            }
            var treeId = this.curTree.treeId
            Util.open(
                {
                    component: FormImport,
                    curVm: this,
                    widthHeight: ['800px', '600px'],
                    title: this.i18n('list.importDialog','对话框方案导入'),
                    data: {
                        treeId: treeId,
                        callback: function (params) {
                            let self = this;
                            FormBoListApi.doImport(params).then(res => {
                                this.isSpinning = false;
                                if (!res.success) {
                                    self.$confirm({
                                        title: self.i18n('warning','警告'),
                                        content: self.i18n('importFail','导入失败！'),
                                        cancelText: self.$ti18('rxForm.cancelBtn','取消')
                                    });
                                    return;
                                }
                                self.getUpdataSqls(res.data);
                            });
                        }
                    }
                }, function (action) {
                }
            );
        },
        changeAppId(selectedRows){
            FormBoListApi.saveList(selectedRows);
        }
    }
}
</script>
<style scoped>

</style>

